package org.micode.common.domain.base;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

/**
 * 缓存对象基类
 */
@Data
public abstract class BaseCache implements IBaseCache {

    /**
     * 缓存过期时间，存储时间点，超过这个时间点就过期
     */
    @JsonIgnore
    private Long expireTime;

    /**
     * 留存时间(秒)
     */
    @JsonIgnore
    private Long retentionSeconds;

    /**
     * 重置时间(秒)
     */
    private Long resetSeconds;

    public BaseCache() {
    }

    public BaseCache(long retentionSeconds, long resetSeconds) {
        this.retentionSeconds = retentionSeconds;
        this.resetSeconds = resetSeconds;

        this.expireTime = System.currentTimeMillis() + readRetentionMS();
    }

    public long readRetentionMS() {
        return retentionSeconds * 1000;
    }

    public long readResetMS() {
        return resetSeconds * 1000;
    }

    public long getRetentionSeconds() {
        return retentionSeconds;
    }

    public boolean resetExpireTime() {
        long currentTime = System.currentTimeMillis();

        // 剩余时间(毫秒)
        long surplusMS = expireTime - currentTime;
        if (surplusMS < readResetMS()) {
            // 剩余时间 小于 重置时间，就需要重置
            expireTime = currentTime + readRetentionMS();
            return true;
        }
        return false;
    }

    public boolean alreadyExpired() {
        return expireTime < System.currentTimeMillis();
    }

    @Override
    public String toString() {
        return "expireTime=" + expireTime +
                ", retentionSeconds=" + retentionSeconds +
                ", resetSeconds=" + resetSeconds;
    }

}
